<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>添删改查</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
        #name,
        #city {
            width: 200px;

        }

        tbody tr,
        .table th {
            text-align: center;
        }

        .searchBox {
            width: 500px;
            display: flex;
            align-items: center;
        }

        .searchBox>div {
            margin-right: 10px;
        }

        #searchBtn,
        #clearBtn,
        #addBtn {
            padding: 0 20px;
            height: 40px;
            margin-right: 10px;
        }
    </style>

</head>

<body>
    <div class="searchBox">
        <div class="input-group input-group-lg">
            <span class="input-group-addon">名称</span>
            <input id="name" type="text" class="form-control" placeholder="请输入名称" />
        </div>
        <div class="input-group input-group-lg">
            <span class="input-group-addon">城市</span>
            <input id="city" type="text" class="form-control" placeholder="请输入城市" />
        </div>
        <button id="searchBtn" type="button" class="btn btn-info">搜索</button>
        <button id="clearBtn" type="button" class="btn btn-primary">重置</button>
        <button id="addBtn" type="button" class="btn btn-success" data-target="#ModalBox" data-toggle="modal">
            添加
        </button>
    </div>
    <!-- 表格 -->
    <table class="table table-striped">
        <thead>
            <tr>
                <th>名称</th>
                <th>城市</th>
                <th>邮编</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- <tr>
          <td>Tanmay</td>
          <td>Bangalore</td>
          <td>560001</td>
        </tr>
        <tr>
          <td>Sachin</td>
          <td>Mumbai</td>
          <td>400003</td>
        </tr>
        <tr>
          <td>Uma</td>
          <td>Pune</td>
          <td>411027</td>
        </tr> -->
        </tbody>
    </table>

    <!-- 模态框-添、删、改 -->
    <div class="modal fade" id="ModalBox" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="ModalLabel">modalTitle</h4>
                </div>
                <div class="modal-body">
                    <!-- <div>
                        姓名：<input type="text" id="userName">
                    </div>
                    <div>
                        城市：<input type="text" id="userCity">
                    </div>
                    <div>
                        邮编：<input type="text" id="userCode">
                    </div> -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary confirm">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>


    <script>
        let data = [
            { id: 1, name: "tanmay", city: "chengdu", code: "600000" },
            { id: 2, name: "tanmay1", city: "重庆", code: "600001" },
            { id: 3, name: "tanmay11", city: "chengdu", code: "600100" },
            { id: 4, name: "tanmay12", city: "chengdu", code: "611000" },
            { id: 5, name: "张三", city: "上海", code: "611001" },
            { id: 6, name: "张", city: "上海", code: "611002" },
            { id: 7, name: "tanmay13", city: "北京", code: "611003" },
            { id: 8, name: "李四", city: "深圳", code: "611001" },
        ];
        let searchData = [];
        // let copyData = $.extend(true, [], data)
        // 动态渲染数据
        function render(data) {
            // 清空
            $("tbody").empty();

            for (let i = 0; i < data.length; ++i) {
                const item = data[i];
                $("tbody").append(`
                <tr>
                    <td>${item.name}</td>
                    <td>${item.city}</td>
                    <td>${item.code}</td>
                    <td>
                        <button type="button" class="btn btn-warning editItem" data-id="${item.id}" data-target="#ModalBox" data-toggle="modal">修改</button>
                        <button type="button" class="btn btn-danger deleteItem" data-id="${item.id}" data-target="#ModalBox" data-toggle="modal">删除</button>
                    </td>
                </tr>
                `);
            }
        }

        render(data);

        // 为名称添加搜索
        $("#searchBtn").on("click", function () {
            searchData = []
            // 获取名称
            const name = $("#name").val();
            // 获取城市
            const city = $("#city").val();
            for (let i = 0; i < data.length; ++i) {
                const item = data[i];
                const condition =
                    (!name || item.name.includes(name)) &&
                    (!city || item.city.includes(city));
                if (condition) {
                    searchData.push(item);
                }
            }
            // console.log(searchData);
            render(searchData);
        });

        // 重置
        $("#clearBtn").on("click", function () {
            $("#name").val("");
            $("#city").val("");
            render(data);
        })

        // 添加
        $("#addBtn").on("click", function () {
            $("#ModalLabel").text("添加")
            $(".modal-body").empty().append(`
                <div>
                    姓名：<input type="text" id="userName">
                </div>
                <div>
                    城市：<input type="text" id="userCity">
                </div>
                <div>
                    邮编：<input type="text" id="userCode">
                </div>
            `)
        })

        // 修改
        $("tbody").on("click", ".editItem", function (event) {
            $("#ModalLabel").text("修改");
            $(".modal-body").empty().append(`
                <div class="editBox">
                    <div>
                        姓名：<input type="text" id="userName">
                    </div>
                    <div>
                        城市：<input type="text" id="userCity">
                    </div>
                    <div>
                        邮编：<input type="text" id="userCode">
                    </div>
                </div>
                
            `)
            const dataId = parseInt($(event.target).attr("data-id"));
            let newData = null;
            if (searchData.length !== 0) {
                newData = searchData;
            } else {
                newData = data;
            }
            const currentItem = newData.find(function (item) {
                return item.id === dataId
            })
            console.log("currentItem", currentItem)
            $("#userName").val(currentItem.name)
            $("#userCity").val(currentItem.city)
            $("#userCode").val(currentItem.code)
            $(".editBox").attr("id", currentItem.id)
        })

        // 删除
        $("tbody").on("click", ".deleteItem", function (event) {
            $("#ModalLabel").text("删除");
            const dataId = parseInt($(event.target).attr("data-id"));
            let newData = null;
            if (searchData.length !== 0) {
                newData = searchData;
            } else {
                newData = data;
            }

            for (let i = 0; i < newData.length; i++) {
                if (newData[i].id === dataId) {
                    $(".modal-body").empty().append(`
                        <div id=${newData[i].id}>是否删除 ${newData[i].name}</div>
                    `)
                    return;
                }
            }
        })


        // 确定按钮
        $(".confirm").on("click", function () {
            let newData = null;
            if (searchData.length !== 0) {
                newData = searchData;
            } else {
                newData = data;
            }

            if ($("#ModalLabel").text() === "添加") {
                const addName = $("#userName").val().trim();
                const addCity = $("#userCity").val().trim();
                const addCode = $("#userCode").val().trim();
                let maxLength = data.length;
                let addObj = {
                    id: maxLength + 1,
                    name: addName,
                    city: addCity,
                    code: addCode,
                }
                data.push(addObj);
            }

            if ($("#ModalLabel").text() === "修改") {
                const newName = $("#userName").val().trim();
                const newCity = $("#userCity").val().trim();
                const newCode = $("#userCode").val().trim();
                const dataId = parseInt($(".editBox").attr("id"));
                let editObj = {
                    name: newName,
                    city: newCity,
                    code: newCode,
                }
                for (let i = 0; i < newData.length; i++) {
                    if (newData[i].id === dataId) {
                        newData.splice(i, 1, editObj)
                    }
                }
            }

            if ($("#ModalLabel").text() === "删除") {
                const dataId = parseInt($(".modal-body>div").attr("id"));
                for (let i = 0; i < newData.length; i++) {
                    if (newData[i].id === dataId) {
                        newData.splice(i, 1)
                    }
                }
            }
            render(newData);
            $('#ModalBox').modal('hide')
        })
    </script>
</body>

</html>